
from django.http import HttpResponse
from django.views.generic import View
from rest_framework.generics import GenericAPIView
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import News
from .serializers import NewsGetSerializer, NewsSerializer

"""
 DRF实现CBV
 GenericAPIview
"""

class NewsView(GenericAPIView):
    queryset = News.objects.all()
    serializer_class = NewsSerializer
    def get(self, request, *args, **kwargs):
        if 'pk' in kwargs:
            new = self.get_object()  #根据主键获取单条数据
            serializer =self.get_serializer(instance=new)
            return Response(serializer.data, status=200)
        # 关联查询，只查询category有值的
        # queryset = self.get_queryset().select_related('category')
        queryset = self.get_queryset()
        serializer = NewsSerializer(instance=queryset, many=True)
        return Response(serializer.data, status=200)
    def post(self, request: Request):
        serializer = self.get_serializer(data=request.data)
        # 有异常抛出
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=200)
        return Response(serializer.errors, status=404)
    def put(self, request: Request,pk):
        instance = self.get_object()
        serializer = self.get_serializer(instance=instance, data=request.data)
        # 有异常抛出
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=200)
        return Response(serializer.errors, status=404)
    def delete(self, request: Request, pk):
        self.get_object().delete()
        return Response({'code': 200, 'msg': '删除成功'}, status=200)
